#include "Hero.h"
#include "../../data/Creator.h"
#include "../../data/GameInfo.h"

void Hero::OnUpdate(double delta)
{
    if (isChant) {
        animCurrent->OnUpdate(delta);
        return;
    }
    if (isRelease) {
        animCurrent->OnUpdate(delta);
        return;
    }
    Character::OnUpdate(delta);
}

void Hero::ResetStatus()
{
    isChant = isRelease = false;
    Character::ResetStatus();
}

void Hero::Attack()
{
    if (isChant || isRelease) return;
    Character::Attack();
}

void Hero::Chant()
{
    if (isChant || isRelease || isRigidity || isDie) return;

    Mix_PlayChannel(-1, chantMix, 0);
    ResetStatus();
    animChant[facing].Reset();
    animCurrent = &animChant[facing];
    isChant = true;
}

void Hero::Release()
{
    if (isChant || isRelease || isRigidity || isDie) return;
    Mix_PlayChannel(-1, releaseMix, 0);
    ResetStatus();
    animRelease[facing].Reset();
    animCurrent = &animRelease[facing];
    isRelease = true;
}

void Hero::ReleaseSkill(uint16_t idx)
{
    if (idx >= skillList.size()) {
        return;
    }
    if (isRelease || isChant || isRigidity) {
        return;
    }
    if (GameInfo::skillConsume[skillList[idx]] > mp) {
        return;
    }
    mp -= GameInfo::skillConsume[skillList[idx]];
    Release();
    auto skill = Creator::CreateSkill(skillList[idx]);
    Mix_PlayChannel(-1, skill->skillMix, 0);
    GameVector pos;
    int angle = 0;
    switch (facing) {
        case Facing::Down:
            pos = {position.x, position.y + skill->shape.w / 2};
            angle = 90;
            break;
        case Facing::Left:
            pos = {position.x - skill->shape.w / 2, position.y};
            angle = 180;
            break;
        case Facing::Right:
            pos = {position.x + skill->shape.w / 2, position.y};
            angle = 0;
            break;
        case Facing::Up:
            pos = {position.x, position.y - skill->shape.w / 2};
            angle = 270;
            break;
        default:
            break;
    }
    skill->direction = pos - position;
    skill->position = pos;
    skill->angle = angle;
    skill->id = id;
    skill->facing = facing;
    animRelease[facing].onFinished = [skill, this] {
        GameInfo::Instance().skills.emplace_back(skill);
        isRelease = false;
    };
}